package cn.wizzer.app.web.modules.controllers.platform.bus.onlyoffice;

import cn.wizzer.app.onlyoffice.modules.dto.Callback;
import cn.wizzer.app.onlyoffice.modules.services.impl.CallbackHandler;
import cn.wizzer.framework.base.Result;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CrossOriginFilter;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

@IocBean
public class CallBackController {
    @Inject
    private CallbackHandler callbackHandler;

    @Inject
    private cn.wizzer.app.onlyoffice.modules.services.Callback callback;


    @At("/callback")
    @Ok("raw")
    public String track(HttpServletRequest request, @Param("fileId") String fileId) throws IOException {
        StringBuilder bodyStr = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            bodyStr.append(line);
        }
        String parameter = bodyStr.toString();
        //System.out.println("保存文档，参数值："+parameter);
        Callback body = new Callback();
        if(Strings.isNotBlank(parameter)) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            body = mapper.readValue(parameter, Callback.class);
        }
        int error = callbackHandler.handle(body, fileId);
        //System.out.println("保存文档，返回值："+error);
        return "{\"error\":" + error + "}";
    }


}
